export function addCookie(name: string, value: string, expiresHours: number): void {
	let cookieString = `${name}=${escape(value)}`;
	if (expiresHours > 0) {
		const date = new Date();
		date.setTime(date.getTime() + expiresHours * 1000);
		cookieString = `${cookieString};expires=${date.toUTCString()}`;
	}
	document.cookie = cookieString;
}

export function setCookieValue(name: string, value: string, expiresHours: number): void {
	let cookieString = `${name}=${escape(value)}`;
	if (expiresHours > 0) {
		const date = new Date();
		date.setTime(date.getTime() + expiresHours * 1000);
		cookieString = `${cookieString};expires=${date.toUTCString()}`;
	}
	document.cookie = cookieString;
}

export function getCookieValue(name: string): string | undefined {
	const strCookie = document.cookie;
	const arrCookie = strCookie.split("; ");
	for (const cookie of arrCookie) {
		const arr = cookie.split("=");
		if (arr[0] === name) {
			return unescape(arr[1]);
		}
	}
}

export const cellphoneReg: RegExp = /^1[356789]\d{9}$/;
export const cellphoneReg1: RegExp = /^\+\d{2}1[356789]\d{9}$/;

export function cellphoneValidator(rule: any, value: string): Promise<void> {
	if (value && value.length > 0) {
		if (cellphoneReg.test(value) || cellphoneReg1.test(value)) {
			return Promise.resolve();
		} else {
			return Promise.reject(new Error("请输入正确的手机号"));
		}
	} else {
		return Promise.resolve();
	}
}

export function testPasswordStrength(password: string): number {
	// 长度少于6位直接不合格
	if (password.length < 6) {
		return 0;
	} else {
		const numbers = /[0-9]+/g;
		const lowerLetters = /[a-z]+/g;
		const upperLetters = /[A-Z]+/g;
		const others = /[^0-9a-zA-Z]+/g;
		// var others = /\W+|\D+/g;
		let strength = 0;
		if (numbers.test(password)) {
			strength += 1;
		}
		if (lowerLetters.test(password)) {
			strength += 1;
		}
		if (upperLetters.test(password)) {
			strength += 1;
		}
		if (others.test(password)) {
			strength += 1;
		}
		return strength;
	}
}

export function cellPhoneValidator(rule: any, value: string): Promise<any> | void {
	if (value && value.length > 0) {
		if (/^1[356789]\d{9}$/.test(value)) {
			return Promise.resolve();
		} else {
			return Promise.reject(new Error("请输入正确的手机号码"));
		}
	} else {
		return Promise.resolve();
	}
}

/**
 * 校验是否是正确的邮箱地址
 * @param rule
 * @param value
 * @returns
 */
export function emailValidator(rule: any, value: string): Promise<any> | void {
	if (value && value.length > 0) {
		const rex = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
		if (rex.test(value)) {
			return Promise.resolve();
		} else {
			return Promise.reject(new Error("请输入正确的邮箱地址"));
		}
	} else {
		return Promise.resolve();
	}
}
